﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using MavlinkPacketViewer.PacketViewer;
using SLPropertyGrid;

namespace MavlinkDebugger.PacketViewer
{
	public class StringValueEditor : ValueEditorBase
	{
		TextBox textBox;
        Button button;

		public StringValueEditor(PropertyGridLabel label, PropertyItem property)
			: base(label, property)
		{
            var grid = new Grid();
            grid.ColumnDefinitions.Add(new ColumnDefinition());
            grid.ColumnDefinitions.Add(new ColumnDefinition());
            grid.Height = 20;
            this.Content = grid;

			textBox = new TextBox();
			textBox.Height = 20;
			if (null != property.Value)
				textBox.Text = property.Value.ToString();
			textBox.IsReadOnly = !this.Property.CanWrite;
			textBox.Foreground = this.Property.CanWrite 
                ? new SolidColorBrush(Colors.Black) 
                : new SolidColorBrush(Colors.Gray);
            textBox.Background = new SolidColorBrush(Colors.White);
            textBox.BorderThickness = new Thickness(0);
			textBox.Margin = new Thickness(0);
            textBox.Padding = new Thickness(2);
            textBox.GotFocus += textBox_GotFocus;
            textBox.AcceptsReturn = true;

            grid.Children.Add(textBox);


            if (this.Property.CanWrite && property.PropertyType == typeof(string))
            {
                button = new Button() { Content = "..." };
                button.Margin = new Thickness(1);
                button.SetValue(Grid.ColumnProperty, 1);
                grid.Children.Add(button);
                grid.ColumnDefinitions[1].Width = new GridLength(20);
            }
            else
                Grid.SetColumnSpan(textBox, 2);

            this.GotFocus += StringValueEditor_GotFocus;
		}

        void StringValueEditor_GotFocus(object sender, RoutedEventArgs e)
        {
            if (button == null || !button.IsFocused)
            {
                textBox.Focus();
            }
        }

        void textBox_GotFocus(object sender, RoutedEventArgs e)
        {
            textBox.SelectAll();
        }
	}
}
